<?php
namespace Admin\Controller;

use Think\Controller;
use Common\Util\Page;
use Common\Util\UploadHandler;
use Common\Controller\AdminbaseController;
use Common\Util\BankCard;

/**
 * 订单类
 *
 */
class OrderController extends AdminbaseController {
    public function index(){
    	$OrderModel = D('Order');
    	$where = array();

    	$beautyId = I('get.beauty_id');
    	$beauticianId = I('get.beautician_id');
    	
    	$orderNumber = I('get.order_number');
    	$mobile = I('get.mobile');
    	$serviceName = I('get.service_name');
    	$starTime = I('get.start_time');
    	
    	if ($orderNumber) {
    		$where ['o.order_number'] = $orderNumber;
    	}
    	 
    	if ($mobile) {
    		$where ['u.mobile'] = $mobile;
    	}
    	
    	if ($serviceName) {
    		$where ['o.service_name'] = $serviceName;
    	}
    	
    	if ($beauticianId) {
    		$where ['o.beautician_id'] = $beauticianId;
    	}
    	
    	if ($beautyId) {
    		$where ['o.beauty_id'] = $beautyId;
    	}
    	
    	if ($starTime) {
    		$endTime = I('get.end_time');
    		$where ['o.created'] = array(array('gt', strtotime($starTime.' 00:00:00')));
    		if ($endTime) {
    			$endTimeStamp = strtotime($endTime.' 23:59:59');
    		} else {
    			$endTimeStamp = time();
    		}
    		$where ['o.created'] [] = array('lt', $endTimeStamp);
    	}
    	
   		$count = $OrderModel->where($where)->count();
   		$page = $this->page($count, 20);
    	$list = $OrderModel->field(array(
	    		'o.*',
	    		'b.name' => 'beautician_name',
	    		'bp.name'	=> 'beauty_name',
    			'u.username' => 'order_user_name',
    			'u.mobile'
    		))
    		->join('o left join '.C('DB_PREFIX').'beautician as b on o.beautician_id=b.id')
    		->join('left join '.C('DB_PREFIX').'beauty_parlor as bp on o.beauty_id=bp.id')
    		->join('left join '.C('DB_PREFIX').'user as u on o.user_id=u.id')
    		->where($where)
    		->order('created desc')->limit($page->firstRow. ','. $page->listRows)
    	->select();
    	$this->assign('list', $list);
    	$this->assign('Page', $page->show('Admin'));
    	$this->display();
    }

    public function change() {
        if (IS_POST) {
            $id  = I ('post.order_id');
            $orderTime = I('post.order_time');

            $OrderModel = D('Order');
            $orderInfo = $OrderModel->getOrderInfo($id);

            $orderDate = date("Y-m-d", $orderTime);
            $dayStart = strtotime ( $orderDate . ' 00:00:00' );
            $dayEnd = strtotime ( $orderDate . ' 23:59:59' );
            $orderDayStart = strtotime ( $orderDate . ' 08:00:00' );
            $orderDayEnd = strtotime ( $orderDate . ' 22:00:00' );
            	
            $ScheduleModel = M('schedule');
            $setting = $ScheduleModel->where(array('uid' => $orderInfo ['beautician_id']))->order('CurrentDate DESC')->limit(1)->find();
            //检测设置的日程
// 			if ($setting) {
// 				$setting = unserialize($setting ['workTime']);
// 			} else {
// 				$this->assign('content', '您预约的时间段，该美容师繁忙，无法为您提供服务。请选择其它美容师');
// 				$this->display('Public/nodata');
// 				exit();
// 			}
            
            //下单日起的日程设置
            $setting = isset($setting [$dayStart])?$setting [$dayStart]:array();
            $canOrder = false;
            if (!$setting) {
            	$canOrder = true;
// 				$this->assign('content', '您预约的时间段，该美容师繁忙，无法为您提供服务。请选择其它美容师');
// 				$this->display('Public/nodata');
// 				exit();
            } else {
            	foreach ($setting as $key => $value) {
            		$hour = ceil($item ['service_time']/60);
            
            		if ($value ['start'] >= $orderTime &&
            		$value ['end'] > (($hour + 1) * 60  + $orderTime)) {
            			$canOrder = true;
            		}
            	}
            }
            	
            //首先判断设置的日程里面的时间是否可预约
            if (!$canOrder) {
            	$this->ajaxReturn(array('status' => 0, 'message' => '您改签的时间段，该美容师繁忙，无法为您提供服务。请选择其它美容师'));
            }
            
            $existOrder = $OrderModel->checkCanOrder($orderInfo ['beautician_id'], $orderTime, $orderDayStart, $orderTime + ($hour + 1) * 3600);
            if ($existOrder) {
            	$this->ajaxReturn(array('status' => 0, 'message' => '您改签的时间段，该美容师繁忙，无法为您提供服务。请选择其它美容师'));
            }
            
            $OrderModel->startTrans();
            $result = $OrderModel->where(array('id' => $id))->save(array('order_time' => $orderTime));
            if ($result) {
                $changeModel = M('order_change');

                $data = array('old_order_time' => $orderInfo ['order_time'], 
                        'new_order_time' => $orderTime,
                        'order_id'  => $id,
                        'created' => time()
                    );
                $changeResult = $changeModel->add($data);

                if (!$changeResult) {
                    $OrderModel->rollback();
                    $this->ajaxReturn(array('status' => 0));
                }

                $OrderModel->commit();
                $this->ajaxReturn(array('status' => 1));
            } else {
                $this->ajaxReturn(array('status' => 0));
            }
        } else {

            $id = I('get.id');
            $OrderModel = D('Order');
            $orderInfo = $OrderModel->getOrderInfo($id);

            $this->assign('fullUrl', get_full_url());
            $this->assign('today', time());
            $this->assign('id', $id);
            $this->assign('beautician_id', $orderInfo ['beautician_id']);
            $this->display();
        }
    }

    public function changeList() {
        $changeModel = M('order_change');

        $orderNumber = I('get.order_number');
        $mobile = I('get.mobile');
        $starTime = I('get.start_time');
        
        if ($orderNumber) {
            $where ['o.order_number'] = $orderNumber;
        }
         
        if ($mobile) {
            $where ['u.mobile'] = $mobile;
        }
        
        if ($starTime) {
            $endTime = I('get.end_time');
            $where ['oc.created'] = array(array('gt', strtotime($starTime.' 00:00:00')));
            if ($endTime) {
                $endTimeStamp = strtotime($endTime.' 23:59:59');
            } else {
                $endTimeStamp = time();
            }
            $where ['oc.created'] [] = array('lt', $endTimeStamp);
        }
        
        $count = $changeModel->count();
        $page = $this->page($count, 20);
        $list = $changeModel->alias('oc')->field(array(
                'oc.old_order_time',
                'o.*',
                'u.username' => 'order_user_name',
                'u.mobile'
            ))
            ->join('left join '.C('DB_PREFIX').'order as o on oc.order_id=o.id')
            ->join('left join '.C('DB_PREFIX').'user as u on o.user_id=u.id')
            ->where($where)
            ->order('oc.created desc')->limit($page->firstRow. ','. $page->listRows)
        ->select();
        $this->assign('list', $list);
        $this->assign('Page', $page->show('Admin'));

        $this->display();
    }
    
    public function detail() {
    	$id = I ('get.id');
    	$OrderModel = D('Order');
    	$orderInfo = $OrderModel->getOrderInfo($id);
    	
    	$user = D('User')->getUserById($orderInfo ['user_id']);
    	$beautician = D('Beautician')->getBeauticianInfo($orderInfo ['beautician_id']);
    	$beauty = D('BeautyParlor')->getBeautyInfo($orderInfo ['beauty_id']);
    	
    	$this->assign('user', $user);
    	$this->assign('beautician', $beautician);
    	$this->assign('beauty', $beauty);
    	$this->assign('one', $orderInfo);
    	$this->display();
    }
    
    public function delete() {
    	$OrderModel = D('Order');
    	
    	if (!IS_POST) {
    		$id = I ('get.id');
    		
    		$result = $OrderModel->where(array('id' => $id))->save(array('status' => 0));
    		if ($result) {
    			$operation = array('operation_object_id' => $id);
    			\Think\Hook::listen('operation', $operation);
    		
    			$this->ajaxReturn(array('status' => 1, 'url' => U('/Admin/Order/index')));
    		} else {
    			$this->ajaxReturn(array('status' => 0));
    		}
    	} else {
    		$ids = I ('post.ids');
    		if (count($ids) == 1) {
    			$where = array('id' => $ids[0]);
    			$result = $OrderModel->where($where)->save(array('status' => 0));
    		} else {
    			$where ['id'] = array('in', implode(',',$ids));
    			$result = $OrderModel->where($where)->save(array('status' => 0));
    		}
    	
    		if (!$result) {
    			$this->ajaxReturn(array('status' => 0 ));
    		}
    	
    		foreach ($ids as $beautyId) {
    			$operation = array('operation_object_id' => $beautyId);
    			\Think\Hook::listen('operation', $operation);
    			$OrderModel->clearCache($beautyId);
    		}
    		
    		$this->ajaxReturn(array('status' => 1, 'url' => U('index')));
    	}
    }
    
    public function refund() {
    	$OrderModel = D('Order');
    	
    	if (IS_POST) {
    		$id = I('post.id');
    		$orderInfo = $OrderModel->where(array('id' => $id))->find();
    		if ($orderInfo ['status'] != 1) {
    			$this->error('该订单不能进行退款操作', U('index'));
    			exit;
    		}
    		
    		$OrderModel->startTrans();
    		$cardModel = D ( '/Home/Model/Card' );
    		$cardHolder = I ( 'post.cardHolder' );
    		$card = I ( 'post.card' );
    			
    		$target_id=$orderInfo ['user_id'];
    		$where = array('target_id' => $target_id, 'card' => $card);
    		$cardBindRecord = $cardModel->where($where)->find();
    		if (!$cardBindRecord) {
    			$BankCard = new BankCard ();
    			$cardInfo = $BankCard->query ( $card );
    			if (!$cardInfo) {
    				$this->ajaxReturn(array('status' => 0, 'message' => '获取银行卡信息失败'));
    			}
    		
    			$last_four_number = substr ( $card, -4 );
    			$bank_name = $cardInfo ['bank_name'];
    			$card_type = $cardInfo ['card_type'];
    			$data = array (
    					'cardHolder' => $cardHolder,
    					'card' => $card,
    					'bank_name' => $bank_name,
    					'card_type' => $card_type,
    					'target_id' => $target_id,
    					'last_four_number' => $last_four_number,
    					'status'	=> 1,
    					'created' => time()
    			);
    			
    			$card_id = $cardModel->add ( $data );
    			if (!$card_id) {
    				$this->error('获取银行卡信息失败');
    				exit;
    			}
    		} else {
    			$card_id = $cardBindRecord ['id'];
    			if ($cardBindRecord ['status'] != 1) {
    				$cardModel->where($where)->save(array('status' => 1));
    			}
    		}
    		
    		$result = $OrderModel->where(array('id' => $id))->save(array('status' => 7));
    		if ($result) {
    			$RefundModel = M('refund_record');
    			
    			$refundData = array(
    				'order_id' => $id, 
    				'card_id' => $card_id,
    				'bank_full_name' => I('post.bank_full_name'),
    				'remark' => I('post.remark'),
    				'created' => time()
    			);
    			$refundResult = $RefundModel->add($refundData);
    			if (!$refundResult) {
    				$OrderModel->rollback();
    				$this->error('创建退款记录失败');
    				exit;
    			}
    			
    			$operation = array('operation_object_id' => $id);
    			\Think\Hook::listen('operation', $operation);
    			 
    			$OrderModel->commit();
    			$OrderModel->clearCache($id);
    			$this->ajaxReturn(array('status' => 1, 'url' => U('/Admin/Order/index')));
    		} else {
    			$this->ajaxReturn(array('status' => 0));
    		}
    	} else {
    		$id = I ('get.id');
    		$orderInfo = $OrderModel->where(array('id' => $id))->find();
    		if ($orderInfo ['status'] != 1) {
    			$this->error('该订单不能进行退款操作', U('index'));
    			exit;
    		}
    		
    		$this->assign('order_id', $id);
    		
    		$this->display('refund');
    	}
    }
}